单元测试

用Python搭建自动化测试框架,我们需要组织用例以及测试执行,推荐Python的标准库——unittest。
unittest是xUnit系列框架中的一员,如果你了解xUnit的其他成员,那你用unittest来应该是很轻松的,它们的工作方式都差不多。

官方说明文档: https://docs.python.org/3/library/unittest.html
The unittest module is actually a testing framework that was originally inspired by JUnit. It currently supports test automation, the sharing of setup and shutdown code, aggregating tests into collections and the independence of tests from the reporting framework.

Unittest框架支持以下4个概念:

  • Test Fixture –对一个测试用例环境的搭建和销毁。 A fixture is what is used to setup a test so it can be run and also tears down when the test is finished. For example, you might need to create a temporary database before the test can be run and destroy it once the test finishes.
  • Test Case – 一个TestCase的实例就是一个测试用例,通过运行这个测试单元,可以对某一个问题进行验证。 The test case is your actual test. It will typically check (or assert) that a specific response comes from a specific set of inputs. The unittest frameworks provides a base class called TestCase that you can use to create new test cases.
  • Test Suite – 多个测试用例集合在一起,就是TestSuite。 The test suite is a collection of test cases, test suites or both.
  • Test Runner – 是来执行测试用例的。 A runner is what controls or orchestrates the running of the tests or suites. It will also provide the outcome to the user (i.e. did they pass or fail). A runner can use a graphical user interface or be a simple text interface.

我们使用PYTHON的单元测试的主要方法是:

  • assert-基础断言,允许用户自己扩展断言;
  • assertEqual(a, b) -检查a和b是否相等;
  • assertNotEqual(a, b) -检查a和b是否不相等;
  • assertIn(a, b) -检查a是否在b中;
  • assertNotIn(a, b) -检查a是否不在b中;
  • assertFalse(a) -检查a的值是否是FALSE;
  • assertTrue(a) -检查a的值是否是TRUE;
  • assertIsInstance(a, b) -检查a的类型是否是“b”;
  • assertRaises(ERROR, A, ARGS)-检查当A使用参数ARGS被调用的时候是否会引发ERROR;

In [21]:
# 一个简单例子, 将该脚本保存为 mymath.py
# 建立一个自己的脚本,定义了 add substract multiply divide 四个数学功能,我们用单元测试来检查它们是否与预期的功能一致!

def add(a, b):
    return a + b
 
def subtract(a, b):
    return a - b
 
def multiply(a, b):
    return a * b
 
def divide(numerator, denominator):
    return float(numerator) / denominator

In [ ]:
# 将以下脚本保存为 test_mymath.py,并运行

"""
构建unittest基本使用方法
1.import unittest 导入unittest库
2.定义一个继承自unittest.TestCase的测试用例类
3.定义setUp和tearDown,在每个测试用例前后做一些辅助工作
4.定义测试用例,函数名字以test开头
5.一个测试用例应该只测试一个方面,测试目的和测试内容应很明确。主要是调用assertEqual、assertRaises等断言方法判断程序执行结果和预期值是否相符。
6.调用unittest.main()启动测试
7.如果测试未通过,会输出相应的错误提示。如果测试全部通过则不显示任何东西,这时可以添加-v参数显示详细信息。
"""

import mymath
import unittest
 
class TestAdd(unittest.TestCase):
    """
    Test the add function from the mymath library
    """
 
    def test_add_integers(self):
        """
        Test that the addition of two integers returns the correct total
        """
        result = mymath.add(1, 2)
        self.assertNotEqual(result, 555)
        self.assertEqual(result, 3)
 
    def test_add_floats(self):
        """
        Test that the addition of two floats returns the correct result
        """
        result = mymath.add(10.5, 2)
        self.assertEqual(result, 12.5)
 
    def test_add_strings(self):
        """
        Test the addition of two strings returns the two string as one
        concatenated string
        """
        result = mymath.add('abc', 'def')
        self.assertEqual(result, 'abcdef')
 
 
if __name__ == '__main__':
    unittest.main()

In [ ]: